﻿@using Microsoft.Extensions.DependencyInjection
@using Microsoft.Extensions.Configuration
@using System.Globalization
@inherits BootstrapComponentBase
@inject IConfiguration Configuration
@inject NavigationManager NavigationManager
@inject ICultureStorage CultureStorage

<div @attributes="@AdditionalAttributes" class="@ClassString">
    <label>请选择语言：</label>
    <Select Value="@SelectedCulture" OnSelectedItemChanged="@SetCulture">
        <Options>
            @foreach (var kv in Configuration.GetSupportCultures())
            {
                <SelectOption Text="@GetDisplayName(kv)" Value="@kv.Name" />
            }
        </Options>
    </Select>
</div>

@code{
    private string? ClassString => CssBuilder.Default("culture-selector")
        .AddClassFromAttributes(AdditionalAttributes)
        .Build();

    private string SelectedCulture { get; set; } = CultureInfo.CurrentUICulture.Name;

    private async Task SetCulture(SelectedItem item)
    {
        if (CultureStorage.Mode == CultureStorageMode.Webapi)
        {
            // 使用 api 方式 适用于 Server-Side 模式
            if (SelectedCulture != item.Value)
            {
                var culture = item.Value;
                var uri = new Uri(NavigationManager.Uri).GetComponents(UriComponents.PathAndQuery, UriFormat.Unescaped);
                var query = $"?culture={Uri.EscapeDataString(culture)}&redirectUri={Uri.EscapeDataString(uri)}";

                // use a path that matches your culture redirect controller from the previous steps
                NavigationManager.NavigateTo("/Culture/SetCulture" + query, forceLoad: true);
            }
        }
        else
        {
            var cultureName = item.Value;
            if (cultureName != CultureInfo.CurrentCulture.Name)
            {
                await JSRuntime.InvokeVoidAsync(identifier: "$.blazorCulture.set", cultureName);
                var culture = new CultureInfo(cultureName);
                CultureInfo.CurrentCulture = culture;
                CultureInfo.CurrentUICulture = culture;

                NavigationManager.NavigateTo(NavigationManager.Uri, forceLoad: true);
            }
        }
    }

    private string GetDisplayName(CultureInfo culture)
    {
        return CultureStorage.Mode switch
        {
            CultureStorageMode.Webapi => culture.NativeName,
            _ => culture.Name switch
            {
                "zh-CN" => "中文(中国)",
                "zh-TW" => "中文(台灣)",
                "en-US" => "English (United States)",
                "de-DE" => "Deutsch (Deutschland)",
                _ => ""
            }
        };
    }
}